require('dotenv').config();
const nodemailer = require('nodemailer');
const fs = require('fs');


const transporter = nodemailer.createTransport({
    host: process.env.email_service,  // SMTP 服务器地址
    port: 587,                 // SMTP 端口，常见 587(STARTTLS) 或 465(SSL)
    secure: false,             // 是否使用 SSL/TLS，true 对应 465 端口
    auth: {
        user: process.env.email_user,  // 发件人邮箱
        pass: process.env.email_pass            // 邮箱密码或授权码
    }
}); 

// 生成6位随机数，时间戳的后3位 + 随机数的前3位
const generateVerificationCode = () => {
    let timestamp = Date.now().toString();
    timestamp = timestamp.substring(timestamp.length - 3);
    const randomNum = Math.random().toString().substring(2,5);
    return timestamp + randomNum;
}

const verificationCodes = generateVerificationCode()
//定义邮件内容
const mailOptions = {
    from: `"node登录注册项目" <${process.env.email_user}>`,
    to: '1121624347@qq.com', 
    subject: '【验证码】你的注册验证码', // 邮件主题
    text: '你的注册验证码是：' + verificationCodes + '（5分钟内有效）', // 纯文本内容（备选，若有 HTML 则优先显示 HTML）
    html: fs.readFileSync('./public/html/email.html', 'utf-8').replace('{{code}}', verificationCodes)
};

//发送邮件
const sendEmail = (recipient) => {
    mailOptions.to = recipient;
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.log('❌邮件发送失败：', error.message);
            throw new Error('邮件发送失败：' + error.message);
        }
        console.log('✅邮件发送成功');
    });
    return verificationCodes;
};
module.exports = {
    sendEmail
};